import { ActionReducer, Action } from "@ngrx/store";
import { fromJS, List } from "immutable";

export const UPDATE_DATA = 'UPDATE_DATA';
export const UPDATE_QUOTE = 'UPDATE_QUOTE';
export const ADD_NEW_TABLE = 'ADD_NEW_TABLE';
export const SET_SORT = 'SET_SORT'


export interface SingleTableState {
  id: number;
  sortBy: string;
  isReversed: boolean;
  pageSize?: any;
  originData: any[];
}

export { getId } from "utils";

export class TableData implements SingleTableState {
  id;
  sortBy;
  isReversed = false;
  originData = [];
  constructor(payload) {
    this.id = payload.id;
  }
}

export const tableState: ActionReducer<SingleTableState[]> =
  (state = [], action: Action) => {
    switch (action.type) {
      case UPDATE_DATA:
        return state.map(table => table.id === action.payload.id ? Object.assign({}, table, {
          currentPage: 0,
          totalSize: action.payload.originData.length,
          totalPage: Math.ceil(action.payload.originData.length / table.pageSize),
          originData: action.payload.originData
        }) : table);
      case UPDATE_QUOTE:
        return state.map(table => table.id === action.payload.id ? Object.assign({}, table, updateQuote(table, action)) : table);
      case ADD_NEW_TABLE:
        return [...state, new TableData(action.payload)]
      case SET_SORT:
        return state.map(table => table.id === action.payload.id ? Object.assign({}, table, {
          sortBy: action.payload.sortBy,
          isReversed: table.sortBy === action.payload.sortBy ? !table.isReversed : table.isReversed
        }) : table);
      default: return state;
    }
  }

const updateQuote =
  (table, action) => {
    return Object.assign({}, table, {
      originData: table.originData.map(quote => quote.symbol === action.payload.quote.symbol ? Object.assign({}, quote, action.payload.quote) : quote)
    });
  }